package com.indusfo.spc.job;

import com.google.gson.Gson;
import com.indusfo.spc.service.BoardService;
import com.indusfo.spc.untlis.StringUtils;
import com.indusfo.spc.vo.JSONObject;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.IOException;

/**
 * @author tongyw
 * @date 2020/1/6 9:40
 */
@Component
public class DeviceTubJob implements Job {

    @Resource
    BoardService boardService;
//    private static HashMap<Session, String> timeMap = new HashMap<>();

    public static com.indusfo.spc.job.DeviceTubJob DeviceTubJob;

    @PostConstruct
    public void init() {
        DeviceTubJob = this;
        DeviceTubJob.boardService = this.boardService;
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
        try {
            //获取session
            Session session = (Session) map.get("session");
            //获取查询参数
            //TODO
            String deviceId = (String) map.get("deviceId");
            String dayNumber = (String) map.get("dayNumber");
            String endDate = (String) map.get("endDate");
            if(StringUtils.isEmpty(deviceId)){
                deviceId="0";
            }
            JSONObject result = DeviceTubJob.boardService.queryDatahis(Integer.parseInt(deviceId));
            //获取时间节点
//            String time = timeMap.get(session);
//            if (time == null) {
//                time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
//            }
            //查询逻辑
            //TODO


            //存放时间节点
//            time = sdf.format(new Date());
//            timeMap.put(session, time);

            //对象数据转json
            String json = new Gson().toJson(result);
            //发送消息
            if(session.isOpen()){

                session.getBasicRemote().sendText(json);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
